/**
 * Writed by yura and mak
 */

package wz.legend.handlers;

import org.apache.log4j.Logger;

import java.awt.TrayIcon;
import java.io.IOException;
import java.io.StringReader;
import java.util.LinkedList;
import java.util.List;

import javax.xml.namespace.QName;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.apache.http.HttpEntity;
import org.cyberneko.html.parsers.DOMParser;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import wz.legend.Context;
import wz.legend.HttpContext;
import wz.legend.gui.Tray;
import wz.legend.util.UriConstants;


public class ChatHandler implements ResponseHandler {
    /**
     * Logger for this class
     */
    private static final Logger LOG = Logger.getLogger(ChatHandler.class);

    public void handle(HttpContext httpContext, Context context) {
        String uri = httpContext.getRequest().getRequestLine().getUri();
        if (!uri.contains(UriConstants.CHAT_DATA_PHP)) {
            return;
        }
        try {
            Document document = httpContext.getResponseDocument();
            List<String> messages = getMessages(document);
            if (messages.size() == 0) {
                return;
            }
            StringBuffer buffer = new StringBuffer();
            for (String string : messages) {
                buffer.append(string).append("\n");
            }
            Tray.getInstance().showMessage("Message", buffer.toString(), TrayIcon.MessageType.INFO);
        } catch (Exception e) {
            LOG.error(e, e);
        }
    }

    public List<String> getMessages(Document document) {
        List<String> result = new LinkedList<String>();
        Document chatDocument = getChatDocument(document);
        
        if (chatDocument != null) {
            XPath path = XPathFactory.newInstance().newXPath();
            try {
                NodeList list = (NodeList) path.evaluate("//DIV[@class='cml_def']", chatDocument, XPathConstants.NODESET);
                for (int i = 0; i < list.getLength(); i++) {
                    String message = list.item(i).getTextContent();
                    result.add(message);
                }
            } catch (XPathExpressionException e) {
                LOG.error(e, e);
            }
        }
        return result;
    }

    public Document getChatDocument(Document document) {
        try {
            XPath path = XPathFactory.newInstance().newXPath();
            String string = path.evaluate("/HTML/BODY/SCRIPT", document);
            int end = string.indexOf("<msg_end>';");
            if (end == -1) {
                return null;
            }
            int begin = string.indexOf("parent.chatTextHtml = '");
            String substring = string.substring(begin + 23, end);
            DOMParser parser = new DOMParser();
            parser.parse(new InputSource(new StringReader(substring)));
            return parser.getDocument();
        } catch (Exception e) {
            LOG.error(e, e);
        }
        return null;
    }
    
    

}
